package com.bnd.service.impl;

import com.aliyun.imageaudit20191230.Client;
import com.aliyun.imageaudit20191230.models.ScanTextRequest;
import com.aliyun.imageaudit20191230.models.ScanTextResponse;
import com.aliyun.imageaudit20191230.models.ScanTextResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.bnd.service.ContentSafetyService;
import com.bnd.common.SafetyMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.aliyun.teautil.models.RuntimeOptions;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 内容安全服务实现类
 */
@Slf4j
@Service
public class ContentSafetyServiceImpl implements ContentSafetyService {

    @Value("${ai.green.region:cn-shanghai}")
    private String region;

    /**
     * 构建阿里云客户端
     * @return 配置好的客户端实例
     * @throws Exception 配置异常
     */
    private Client buildClient() throws Exception {
        String ak = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String sk = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        if (ak == null || sk == null) {
            log.warn("[TextScan] AK/SK 未读取到，region={}", region);
        }
        Config config = new Config()
                .setAccessKeyId(ak)
                .setAccessKeySecret(sk)
                .setRegionId(region)
                .setEndpoint("imageaudit.cn-shanghai.aliyuncs.com");
        return new Client(config);
    }

    /**
     * 检测文本是否安全
     * @param text 待检测文本
     * @return 通过返回null；不通过返回违规原因
     */
    @Override
    public String checkText(String text) {
        try {
            if (text == null || text.trim().isEmpty()) { return null; }
            Client client = buildClient();

            // 构造 Labels（参考官方文档的示例）
            List<ScanTextRequest.ScanTextRequestLabels> labels = new ArrayList<>();
            for (String l : new String[]{"spam","ad","politics","abuse","porn","terrorism","contraband","meaningless"}) {
                labels.add(new ScanTextRequest.ScanTextRequestLabels().setLabel(l));
            }
            // 构造 Tasks
            List<ScanTextRequest.ScanTextRequestTasks> tasks = new ArrayList<>();
            tasks.add(new ScanTextRequest.ScanTextRequestTasks().setContent(text));


            ScanTextRequest request = new ScanTextRequest()
                    .setLabels(labels)
                    .setTasks(tasks);

            RuntimeOptions runtime = new RuntimeOptions();
            ScanTextResponse resp = client.scanTextWithOptions(request, runtime);
            ScanTextResponseBody body = resp.getBody();
            Integer httpCode = resp == null ? null : resp.getStatusCode();
            if (httpCode == null || httpCode != 200) {
                log.warn("[TextScan] HTTP异常, status={}, body={}", httpCode, body);
                return "内容安全服务异常";
            }

            // 使用通用 Map 解析，避免模型类差异导致编译失败
            Map<String, Object> map = body.toMap();
            Map data = (Map) firstNonNull(map, "data", "Data");
            if (data == null) return null;
            java.util.List elements = (java.util.List) firstNonNull(data, "elements", "Elements");
            if (elements == null || elements.isEmpty()) return null;
            Map first = (Map) elements.get(0);
            List results = (List) firstNonNull(first, "results", "Results");
            if (results == null) return null;
            for (Object ro : results) {
                java.util.Map r = (java.util.Map) ro;
                Object suggestionObj = firstNonNull(r, "suggestion", "Suggestion");
                String suggestion = suggestionObj == null ? null : suggestionObj.toString();
                Object labelObj = firstNonNull(r, "label", "Label");
                String label = labelObj == null ? "" : labelObj.toString();
                if ("block".equalsIgnoreCase(suggestion)) {
                    return SafetyMessage.BLOCKED_REPLY;
                }
                if ("review".equalsIgnoreCase(suggestion)) {
                    return "疑似敏感，需人工复审: " + label;
                }

            }
            return null;
        } catch (Exception e) {
            log.error("[Aliyun TextScan] 调用失败", e);
            return "内容安全服务调用失败";
        }
    }

    /**
     * 从Map中获取第一个非空值（支持多个键名）
     * @param map 数据Map
     * @param keys 键名数组
     * @return 第一个非空值
     */
    private static Object firstNonNull(Map map, String... keys) {
        if (map == null || keys == null) { return null; }
        for (String k : keys) {
            if (map.containsKey(k)) { return map.get(k); }
        }
        return null;
    }
}